package com.example.community.rest;

import com.example.community.dto.CommentCreateDTO;
import com.example.community.dto.CommentDTO;
import com.example.community.dto.ResultDTO;
import com.example.community.dto.UserDto;
import com.example.community.enums.CommentTypeEnum;
import com.example.community.exception.CustomizeErrorCode;
import com.example.community.model.Comment;
import com.example.community.model.GiteeUser;
import com.example.community.model.User;
import com.example.community.service.CommentService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping(path = "/comment",
                produces = "application/json")
public class CommentResource {

    @Autowired
    private CommentService commentService;

    @PostMapping(consumes = "application/json")
    public Object post(@RequestBody CommentCreateDTO commentCreateDTO,
                       HttpServletRequest request) {

        UserDto userDto = (UserDto) request.getSession().getAttribute("user");
        if (userDto == null || (userDto.getUserType() != 1 && userDto.getUserType() != 2) ) {
            return ResultDTO.errorOf(CustomizeErrorCode.NO_LOGIN);
        }
        if (commentCreateDTO == null || StringUtils.isBlank(commentCreateDTO.getContent())) {
            return ResultDTO.errorOf(CustomizeErrorCode.CONTENT_IS_EMPTY);
        }

        Comment comment = new Comment();
        comment.setIp(userDto.getIp());
        comment.setParentId(commentCreateDTO.getParentId());
        comment.setContent(commentCreateDTO.getContent().replaceAll("\\\\\"","\""));
        comment.setType(userDto.getUserType());
        comment.setGmtModified(System.currentTimeMillis());
        comment.setGmtCreate(System.currentTimeMillis());
        comment.setCommentator(userDto.getId());
        comment.setLikeCount(0L);
        commentService.insert(comment, userDto);
        return ResultDTO.okOf();
    }


//    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
//    @GetMapping(path = "/{id}")
//    public ResultDTO<List<CommentDTO>> comments(@PathVariable(name = "id") Long id) {
//
//        List<CommentDTO> commentDTOS = commentService.listByTargetId(id, CommentTypeEnum.COMMENT);
//        return ResultDTO.okOf(commentDTOS);
//    }
}